package br.com.devteam.base.validator;

import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator(value = "TelefoneValidator")
public class TelefoneValidator implements Validator {

	@Override
	public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
			throws ValidatorException {

		if (arg2 != null && !validate(arg2.toString()))
			throw new ValidatorException(
					new FacesMessage(
							"Telefone no formato inválido. (##) ####-#### ou "
							+ "(##) ####-#####"));
	}

	public static boolean validate(String fone) {

		if (fone != null) {
			fone = fone.replace("-", "").replace("(", "").replace(")", "")
					.replace(" ", "");

			Pattern pattern = Pattern.compile("^([0-9])");

			return (fone.length() == 10 || fone.length() == 11)
					&& pattern.matcher(fone).find();
		}

		return true;
	}

}
